package info.itloser.pltv.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import info.itloser.pltv.R
import info.itloser.pltv.bean.ResItem
import java.util.zip.Inflater

/**
 * 说明：
 * 作者： itloser.info
 * 日期： 2022/2/23 16:28
 * 备注：
 */
class ResAdapter(private val resItems: List<ResItem>, private val context: Context) :
    RecyclerView.Adapter<ResAdapter.ResHolder>() {

    lateinit var onClick: OnClick

    class ResHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvResNo: TextView = itemView.findViewById(R.id.tv_res_no)
        val tvResName: TextView = itemView.findViewById(R.id.tv_res_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResHolder {

        val view = LayoutInflater.from(context).inflate(R.layout.item_res, parent, false)
        return ResHolder(view)

    }

    override fun onBindViewHolder(holder: ResHolder, position: Int) {

        val resItem = resItems[position]

        //直播源id
        holder.tvResNo.text = noToString(resItem.resId)

        //直播源名称
        holder.tvResName.text = resItem.resName

        //是否选中当前源
        if (resItem.isCheck) {
            holder.itemView.setBackgroundColor(0xFF6200EE.toInt())
        } else {
            holder.itemView.setBackgroundColor(0xFFFFFFFF.toInt())
        }

        //点击事件
        holder.itemView.setOnClickListener {
            onClick.onItemClick(position)

            //标记当前项 选中
            checkOne(position)
        }


    }

    override fun getItemCount(): Int {
        return resItems.size
    }


    /**
     * 给 不满2位的数字补位
     */
    private fun noToString(no: Int): String {
        if (no < 10) {
            return "0$no"
        }
        return "$no"
    }

    private fun checkOne(position: Int) {

        for (i in resItems.indices) {

            if (resItems[i].isCheck && position != i) {
                resItems[i].isCheck = false
                this.notifyItemChanged(i)
            }

        }

        resItems[position].isCheck = true
        this.notifyItemChanged(position)

    }

    /**
     * 给外部的接口
     */
    interface OnClick {

        fun onItemClick(position: Int)

    }

}